import React, { useEffect, useState } from 'react';
import { getAllVms, startVm, shutdownVm, pauseVm, forceShutdownVm, cloneVm, deleteVm } from '../api/virtApi'; // 假设存在 cloneVm 接口
import styles from './VmList.module.css';
import { FaPowerOff, FaStop, FaPlay, FaPlug, FaClone, FaTrashAlt } from 'react-icons/fa';
import { Modal, Checkbox, Input } from 'antd';

// Define an interface for the virtual machine object
interface disk {
  size: number;
  path: string;
}
interface graphics {
  ep: string,
  type: string,
}
interface VirtualMachine {
  name: string;
  state: number;
  memory: number;
  vcpu_count: number;
  disks: disk[];
  graphics?: graphics[];
}

// 单位转换函数
function formatBytes(bytes: number, decimals = 2): string {
  if (bytes === 0) return '0 Bytes';

  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

interface Props {
  className: string;
  operation: (type: string, ep: string) => void;
  children: React.ReactNode;
}

const VmListModel: React.FC<Props> = ({ className, operation, children }) => {
  // Move getIconByState function before the component return
  const getIconByState = (state: number) => {
    switch (state) {
      case 1:
        return <FaPlay style={{ color: '#90EE90' }} />;  // 添加浅绿色样式
      case 3:
        return <FaStop />;
      case 5:
        return <FaPowerOff />;
      default:
        return null;
    }
  };

  const [vms, setVms] = useState<VirtualMachine[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [selectedVmForConnection, setSelectedVmForConnection] = useState<VirtualMachine | null>(null);
  const [selectedVmForOperation, setSelectedVmForOperation] = useState<VirtualMachine | null>(null);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [sortBy, setSortBy] = useState<{ field: 'name' | 'memory' | 'vcpu_count'; order: 'asc' | 'desc' }>({
    field: 'name',
    order: 'asc'
  });

  // 过滤和排序虚拟机列表
  const filteredVms = vms
    .filter(vm => vm.name.toLowerCase().includes(searchTerm.toLowerCase()))
    .sort((a, b) => {
      // 优先将在线（状态为 1）的虚拟机排在前面
      if (a.state === 1 && b.state!== 1) {
        return -1;
      } else if (a.state!== 1 && b.state === 1) {
        return 1;
      }
  
      // 如果状态相同，再根据用户选择的排序字段进行排序
      if (sortBy.field === 'name') {
        return sortBy.order === 'asc'
          ? a.name.localeCompare(b.name)
          : b.name.localeCompare(a.name);
      }
      return sortBy.order === 'asc'
        ? a[sortBy.field] - b[sortBy.field]
        : b[sortBy.field] - a[sortBy.field];
    });

  useEffect(() => {
    const fetchVms = async () => {
      try {
        const vmData = await getAllVms();
        setVms(vmData);
      } catch (error) {
        console.error('Error fetching virtual machine list:', error);
        setError('获取虚拟机列表时出错');
      } finally {
        setLoading(false);
      }
    };

    fetchVms();
  }, []);

  const handleStateClick = async (vm: VirtualMachine) => {
    if (vm.state === 5 || vm.state === 3) { // 关机状态
      try {
        await startVm(vm.name); // 调用启动接口
        // 刷新虚拟机列表
        const vmData = await getAllVms();
        setVms(vmData);
      } catch (error) {
        console.error('启动虚拟机时出错:', error);
        setError('启动虚拟机时出错');
      }
    } else { // 运行或暂停状态
      setSelectedVmForOperation(vm); // 仅在其他状态时弹窗
    }
  };

  const [cloneModalVisible, setCloneModalVisible] = useState(false);
  const [cloneName, setCloneName] = useState('');
  const [selectedVmForClone, setSelectedVmForClone] = useState<VirtualMachine | null>(null);

  const showCloneModal = (vm: VirtualMachine) => {
    setSelectedVmForClone(vm);
    setCloneModalVisible(true);
    console.log('cloneModalVisible 状态更新为: ', cloneModalVisible);
  };

  const handleCloneOk = async () => {
    if (selectedVmForClone && cloneName) {
      try {
        await cloneVm(selectedVmForClone.name, cloneName); // 调用克隆接口
        const vmData = await getAllVms();
        setVms(vmData);
        setCloneModalVisible(false);
        setCloneName('');
      } catch (error) {
        console.error('克隆虚拟机时出错:', error);
        setError('克隆虚拟机时出错');
      }
    }
  };

  const handleCloneCancel = () => {
    setCloneModalVisible(false);
    setCloneName('');
  };

  const [selectedVmForDelete, setSelectedVmForDelete] = useState<VirtualMachine | null>(null);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);
  const [selectedDisks, setSelectedDisks] = useState<string[]>([]);
  const [vmDisks, setVmDisks] = useState<string[]>([]);

  const showDeleteModal = (vm: VirtualMachine) => {
    const disks = vm.disks
      .filter(disk => disk.path.startsWith('/var/lib/libvirt'))
      .map(disk => disk.path);
    setVmDisks(disks);
    setSelectedDisks([]);
    setSelectedVmForDelete(vm);
    setDeleteModalVisible(true);
  };

  const handleDeleteOk = async () => {
    if (selectedVmForDelete) {
        try {
            // 无论是否选中磁盘，都传递 selectedDisks 数组，未选中时为空列表
            await deleteVm(selectedVmForDelete.name, selectedDisks);
            const vmData = await getAllVms();
            setVms(vmData);
            setDeleteModalVisible(false);
        } catch (error) {
            console.error('删除虚拟机时出错:', error);
            setError('删除虚拟机时出错');
        }
    }
};

  const handleDeleteCancel = () => {
    // 清理列表，将 vmDisks 和 selectedDisks 重置为空数组
    setVmDisks([]);
    setSelectedDisks([]);
    setDeleteModalVisible(false);
  };

  const handleDiskChange = (checkedValues: string[]) => {
    setSelectedDisks(checkedValues);
  };

  return (
    <div className={className}>
      {/* 虚拟机创按钮 */}
      <div style={{ marginLeft: '10px', height: '39px' }}>{children}</div>
      {/* 添加搜索框 */}
      <div className={styles.searchContainer}>
        <input
          type="text"
          placeholder="搜索虚拟机名称..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className={styles.searchInput}
        />
        <table className={styles.sortTable}>
          <tbody>
            <tr>
              <td className={styles.sortCell}>
                <button
                  onClick={() => setSortBy({ field: 'name', order: sortBy.field === 'name' && sortBy.order === 'asc' ? 'desc' : 'asc' })}
                  className={sortBy.field === 'name' ? styles.active : ''}
                >
                  名称 {sortBy.field === 'name' && <span className={styles.arrow}>{sortBy.order === 'asc' ? '↑' : '↓'}</span>}
                </button>
              </td>
              <td className={styles.sortCell}>
                <button
                  onClick={() => setSortBy({ field: 'memory', order: sortBy.field === 'memory' && sortBy.order === 'asc' ? 'desc' : 'asc' })}
                  className={sortBy.field === 'memory' ? styles.active : ''}
                >
                  内存 {sortBy.field === 'memory' && <span className={styles.arrow}>{sortBy.order === 'asc' ? '↑' : '↓'}</span>}
                </button>
              </td>
              <td className={styles.sortCell}>
                <button
                  onClick={() => setSortBy({ field: 'vcpu_count', order: sortBy.field === 'vcpu_count' && sortBy.order === 'asc' ? 'desc' : 'asc' })}
                  className={sortBy.field === 'vcpu_count' ? styles.active : ''}
                >
                  CPU {sortBy.field === 'vcpu_count' && <span className={styles.arrow}>{sortBy.order === 'asc' ? '↑' : '↓'}</span>}
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      {error && <p style={{ color: 'red' }}>{error}</p>}

      {loading ? (
        <div className={styles.loadingContainer}>
          <div className={styles.loadingSpinner} />
          <p>正在加载虚拟机列表...</p>
        </div>
      ) : filteredVms.length === 0 ? (
        <div className={styles.emptyState}>
          <p>没有找到匹配的虚拟机</p>
        </div>
      ) : (
        <div className={styles.vmItemContainer} style={{ maxHeight: 'calc(100vh - 115px)', overflowY: 'auto' }}>
          {filteredVms.map((vm, index) => (
            <div key={index} className={styles.vmItem}>
              <div className={styles.vmInfo}>
                <strong className={styles.vmName}>{vm.name}</strong>
                <p className={styles.vmStatus}>内存: {formatBytes(vm.memory)}</p>
                <p className={styles.vmStatus}>CPU 数量: {vm.vcpu_count}</p>
              </div>
              {/* 操作图标 */}
              <div className={styles.icons}>
                {/* 开关开关操作按钮 */}
                <div className={styles.iconContainer}>
                  <span
                    className={styles.statusIcon}
                    onClick={() => handleStateClick(vm)}
                    style={{ cursor: 'pointer' }}
                  >
                    {getIconByState(vm.state)}
                  </span>
                </div>

                {/* 连接图标 */}
                <button
                  className={`${styles.iconContainer} ${!vm.graphics || vm.graphics.length === 0 || vm.graphics.every(g => !g.ep) ? styles.disabled : ''
                    }`}
                  onClick={() => setSelectedVmForConnection(vm)}
                  disabled={!vm.graphics || vm.graphics.length === 0 || vm.graphics.every(g => !g.ep)}
                  title="选择连接方式">
                  <FaPlug style={{ color: !vm.graphics || vm.graphics.length === 0 || vm.graphics.every(g => !g.ep) ? '#333' : '#90EE90' }} />
                </button>

                {/* clone */}
                <button
                  className={styles.iconContainer}
                  onClick={() => showCloneModal(vm)}
                  title="克隆虚拟机">
                  <FaClone style={{ color: "#858484" }} />
                </button>

                {/*  delete */}
                <button
                  className={styles.iconContainer}
                  onClick={() => showDeleteModal(vm)}
                  title="删除虚拟机"
                >
                  <FaTrashAlt style={{ color: "#858484" }} />
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* 弹出窗口 */}
      {selectedVmForConnection && (
        <div className={styles.modalOverlay}>
          <div className={styles.modalContent}>
            <h3 style={{
              color: '#1890ff',
              fontSize: '20px',
              fontWeight: '600',
              marginBottom: '20px',
              textAlign: 'center'
            }}>
              {selectedVmForConnection.name} 连接方式
            </h3>
            <div className={styles.graphicsList}>
              {selectedVmForConnection.graphics?.map((graphics, index) => (
                <div
                  key={index}
                  className={`${styles.graphicsItem} ${!graphics.type || !graphics.ep ? styles.disabled : ''
                    }`}
                  onClick={() => {
                    if (graphics.type && graphics.ep) {
                      operation(graphics.type, graphics.ep);
                      setSelectedVmForConnection(null);
                    }
                  }}
                >
                  <span className={!graphics.type || !graphics.ep ? styles.disabledText : ''}>
                    {graphics.type === 'spice' ? 'SPICE 连接' :
                      graphics.type === 'vnc' ? 'VNC 连接' :
                        '未知连接方式'}
                  </span>
                </div>
              ))}
            </div>
            <div style={{ textAlign: 'right', marginTop: '20px' }}>
              <button
                className={styles.closeButton}
                onClick={() => setSelectedVmForConnection(null)}
              >
                关闭
              </button>
            </div>
          </div>
        </div>
      )}

      {selectedVmForOperation && (
        <div className={styles.modalOverlay}>
          <div className={styles.modalContent}>
            <h3 style={{
              color: '#1890ff',
              fontSize: '20px',
              fontWeight: '600',
              marginBottom: '20px',
              textAlign: 'center'
            }}>
              {selectedVmForOperation.name} 操作
            </h3>
            <div className={styles.graphicsList}>
              <div
                className={styles.graphicsItem}
                onClick={async () => {
                  try {
                    await shutdownVm(selectedVmForOperation.name);
                    const vmData = await getAllVms();
                    setVms(vmData);
                    setSelectedVmForOperation(null);
                  } catch (error) {
                    console.error('关闭虚拟机时出错:', error);
                    setError('关闭虚拟机时出错');
                  }
                }}
              >
                关机
              </div>
              <div
                className={styles.graphicsItem}
                onClick={async () => {
                  try {
                    await forceShutdownVm(selectedVmForOperation.name);
                    const vmData = await getAllVms();
                    setVms(vmData);
                    setSelectedVmForOperation(null);
                  } catch (error) {
                    console.error('强制关闭虚拟机时出错:', error);
                    setError('强制关闭虚拟机时出错');
                  }
                }}
              >
                强制关机
              </div>
              <div
                className={styles.graphicsItem}
                onClick={async () => {
                  try {
                    await pauseVm(selectedVmForOperation.name);
                    const vmData = await getAllVms();
                    setVms(vmData);
                    setSelectedVmForOperation(null);
                  } catch (error) {
                    console.error('暂停虚拟机时出错:', error);
                    setError('暂停虚拟机时出错');
                  }
                }}
              >
                暂停
              </div>
              <div
                className={styles.graphicsItem}
                onClick={() => setSelectedVmForOperation(null)}
              >
                取消
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 克隆模态框 */}
      <Modal
        title="克隆虚拟机"
        visible={cloneModalVisible}
        onOk={handleCloneOk}
        onCancel={handleCloneCancel}
        okText="克隆"
        cancelText="取消"
      >
        <Input
          placeholder="请输入新虚拟机名称"
          value={cloneName}
          onChange={(e) => setCloneName(e.target.value)}
        />
      </Modal>


      <Modal
          title="选择要删除的磁盘"
          visible={deleteModalVisible}
          onOk={handleDeleteOk}
          onCancel={handleDeleteCancel}
          okText="删除"
          cancelText="取消"
      >
          <Checkbox.Group
              className={vmDisks.length > 0 ? styles.checkboxGroupBorder : ''}
              options={vmDisks.map(disk => ({
                  label: <span className={selectedDisks.includes(disk) ? styles['selected-disk'] : ''}>{disk}</span>,
                  value: disk
              }))}
              value={selectedDisks}
              onChange={handleDiskChange}
             
          />
      </Modal>
    </div>
  );
};

export default VmListModel;
